<script setup lang="ts">
import type {
  MovieItem,
  ChannelItem,
  EpisodeItem,
  Response,
  TaskItem,
} from "~/types";
import { trim } from "lodash-es";
const autoCheckTaskTimer = ref();
definePageMeta({
  key: (route) => route.fullPath,
});
const route = useRoute();

const id = computed(() => route.params.id as string);

const movieTask = ref<TaskItem>();
const taskRunning = computed(() => movieTask.value?.status == 1);

const { data: movieData } = await useFetch<Response<MovieItem>>(
  "/bsmovie/record",
  {
    baseURL: useRuntimeConfig().public.baseUrl,
    server: false,
    method: "post",
    body: {
      id,
    },
    pick: ["data"],
  }
);
const movieDetail = computed(() => movieData.value?.data || null);

const { data: channeldata } = await useFetch<
  Response<{ list: ChannelItem[]; total: number }>
>("/bsmoviechannel/list", {
  baseURL: useRuntimeConfig().public.baseUrl,
  server: false,
  method: "post",
  body: {
    movieId: id,
    page: 1,
    size: 80,
  },
  pick: ["data"],
});

const channelList = computed(() => channeldata.value?.data?.list || []);

const episodeList = ref<EpisodeItem[]>([]);

const getEpisodeDataRequest = async (channelName: string) => {
  const { data: episodeData } = await useFetch<
    Response<{ list: EpisodeItem[]; total: number }>
  >("/bsmovieepisode/list", {
    baseURL: useRuntimeConfig().public.baseUrl,
    server: false,
    method: "post",
    body: {
      movieId: id,
      channelName,
      page: 1,
      size: 999,
    },
    pick: ["data"],
  });
  episodeList.value = episodeData.value?.data.list || [];
};

const getMovieDetailTaskRequest = async () => {
  const { data } = await useFetch<Response<TaskItem>>(
    "/bstask/record/by/movie",
    {
      baseURL: useRuntimeConfig().public.baseUrl,
      server: false,
      method: "post",
      body: {
        movieId: id,
      },
      pick: ["data"],
    }
  );
  movieTask.value = data.value?.data;
};

const createMovieUpdateTaskRequest = async () => {
  const { data } = await useFetch<Response<string>>("/bstask/create", {
    baseURL: useRuntimeConfig().public.baseUrl,
    server: false,
    method: "post",
    body: {
      status: 0,
      process: 0,
      taskName: movieDetail.value?.movieName + "详情更新",
      movieId: id,
      sourceId: movieDetail.value?.sourceId,
      remark: "",
      type: 0,
    },
  });
  if (data.value?.code === 0) {
    getMovieDetailTaskRequest();
  }
};

const activeIndex = ref(0);
const activeChannelIndex = ref(0);
const setActiveIndex = (index: number) => {
  activeIndex.value = index;
};
const activeEpisodeRecord = computed(() => {
  return episodeList.value[activeIndex.value];
});

const clearDescHandle = (desc: string) => {
  const split = desc.split("电影天堂是一个");
  return split[0];
};

const onChangeChannelHandle = (index: number) => {
  activeChannelIndex.value = index;
  const { channelName } = channelList.value[index];
  getEpisodeDataRequest(channelName);
};

onMounted(() => {
  getMovieDetailTaskRequest();
});

const autoCheckStatus = () => {
  autoCheckTaskTimer.value = setInterval(() => {
    getMovieDetailTaskRequest();
  }, 3000);
};
onMounted(() => {
  autoCheckStatus();
});
onBeforeUnmount(() => {
  clearInterval(autoCheckTaskTimer.value);
});

watch(
  () => channelList.value,
  () => {
    if (channelList.value?.length > 0) {
      const channelName = channelList.value[0].channelName;
      getEpisodeDataRequest(channelName);
    }
  },
  {
    deep: true,
    immediate: true,
  }
);

watch(
  () => taskRunning.value,
  (newValue, oldValue) => {
    if (oldValue && !newValue) {
      if (channelList.value.length > 0) {
        const channelName =
          channelList.value[activeChannelIndex.value].channelName;
        getEpisodeDataRequest(channelName);
      } else {
        reloadNuxtApp();
      }
    }
  },
  { immediate: true }
);
</script>

<template>
  <div pt-20px px-10px>
    <div flex>
      <div font-bold op80>{{ movieDetail?.movieName }}</div>
      <div ml-20px v-if="movieDetail?.movieName">
        <view
          text-gray:90
          cursor-pointer
          v-if="movieTask?.status == 0"
          @click="getMovieDetailTaskRequest"
          >更新任务排队中</view
        >
        <view
          cursor-pointer
          flex
          text-gray:90
          v-else-if="movieTask?.status == 1"
          @click="getMovieDetailTaskRequest"
        >
          <div i-carbon:circle-dash ma animate-spin />
          <div ml-6px>正在更新</div></view
        >
        <view
          v-else
          n-link
          cursor-pointer
          flex
          @click="createMovieUpdateTaskRequest"
        >
          <div class="i-ph:spiral-thin"></div>
          <div ml-6px>更新剧集内容</div>
        </view>
      </div>
    </div>
    <div mt-20px flex>
      <div flex-1 min-w-1200px h-700px v-if="activeEpisodeRecord?.onlineUrl">
        <VideoPlayer :play-url="activeEpisodeRecord?.onlineUrl || ''" />
      </div>
      <div
        flex-1
        min-w-1200px
        h-700px
        flex="~ justify-center items-center"
        bg-gray:10
        text-white:60
        v-else
      >
        <div>未加载资源，更新剧集内容</div>
      </div>

      <div w-400px mx-30px flex-grow-1>
        <div mb-20px flex text-14px>
          <div>
            <div
              w-130px
              block
              bg-gray4:10
              p1
              class="aspect-10/16"
              transition
              duration-400
            >
              <NuxtImg
                v-if="movieDetail?.cover"
                format="webp"
                :src="movieDetail?.cover"
                :alt="movieDetail?.movieName"
                w-full
                h-full
                object-cover
                :style="{
                  'view-transition-name': `item-${movieDetail?.id}`,
                }"
              />
              <div v-else h-full op10 flex>
                <div i-ph:question ma text-4xl />
              </div>
            </div>
          </div>
          <div ml-10px>
            <div font-bold op80 max-w-320px>
              {{ movieDetail?.movieName }}
            </div>
            <div mt-10px op-70>
              <span>导演：</span><span>{{ movieDetail?.director }}</span>
            </div>
            <div mt-10px op-70 line-clamp-3>
              <span>演员：</span><span break-all>{{ movieDetail?.actor }}</span>
            </div>
            <div mt-10px op-70>
              <span>类型：</span><span>{{ movieDetail?.tags }}</span>
            </div>
            <div mt-10px op-70>
              <span>年代：</span><span>{{ movieDetail?.year }}</span>
            </div>
            <div mt-10px op-70>
              <span>地区：</span><span>{{ movieDetail?.region }}</span>
            </div>
          </div>
        </div>
        <div op70 mt-10px line-clamp-6 w-full text-14px mb-10px>
          简介： {{ clearDescHandle(trim(movieDetail?.desc)) }}
        </div>
        <div bg-black p-2>
          <div
            mb-20px
            flex="~ nowrap"
            of-x-auto
            max-w-300px
            whitespace-nowrap
            class="hidden-scrollbar-x"
          >
            <div
              mr-10px
              cursor-pointer
              w-66px
              text-center
              text-15px
              @click="() => onChangeChannelHandle(index)"
              :class="
                activeChannelIndex == index ? 'text-white font-bold' : ' n-link'
              "
              v-for="(item, index) in channelList"
              :key="`channel-${item.id}`"
            >
              {{ item.channelName }}
            </div>
          </div>
          <div
            flex
            flex-wrap
            w-320px
            h-274px
            of-y-auto
            class="hidden-scrollbar-y"
          >
            <div
              v-for="(item, index) in episodeList"
              :key="index"
              :class="
                activeIndex == index ? 'bg-primary text-white' : ' n-link'
              "
              @click="() => setActiveIndex(index)"
              cursor-pointer
              mb-20px
              mr-20px
              w-60px
              h-60px
              rounded
              text-15px
              flex="~ items-center justify-center"
              text-center
            >
              {{ item.name }}
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped></style>
